/**
 * 
 */
package com.autoscript.filter;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.alibaba.fastjson.JSON;
import com.autoscript.utils.SessionMap;
import com.dfhc.util.StringHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.autoscript.ISystemConstant;
import com.autoscript.service.DBSessionService;
import com.autoscript.utils.ContextUtils;
import com.dfhc.securitydb.service.SecurityDBClientService;
import org.springframework.context.ApplicationContext;
import org.springframework.http.HttpHeaders;

/**
 * @author Administrator
 * 权限过滤器
 */

public class PrivilegeFilter implements Filter {
	private static Logger logger=LoggerFactory.getLogger(PrivilegeFilter.class);
	/**
	 * 需要登录url列表
	 */
	private List<String> needLoginUrls;
	private String contextPath;
	private SessionMap sessionMap;
	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		if(needLoginUrls==null) {
			initConfig();
		}
        //处理权限 begin
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse res = (HttpServletResponse) response;

		String appToken = req.getHeader("APP_TOKEN");
		System.out.println("appToken:"+appToken);
		String uri = req.getRequestURI();


		boolean isLogin = false;
		sessionMap = ContextUtils.getBean(SessionMap.class);
		if(sessionMap!=null) {
			Map<String, Object> hSessionMap = sessionMap.get(((HttpServletRequest)request).getHeader(ISystemConstant.SESSION_ID));
			if (hSessionMap == null) {
				setResponseAllOrigin(request, res);
			}else {
				if (hSessionMap.get(ISystemConstant.CURRENT_USER) != null) {
					isLogin = true;
				}
				setResponseAllOrigin(request, res);
				if (needLoginUrls.contains(uri)) {
					if (checkToken(request, res, appToken, isLogin, hSessionMap)) return;
				}
			}
		}
		//验证通过，正常情况
		chain.doFilter(request, response);
	}

	/**
	 * 检查token
	 * @param res
	 * @param appToken
	 * @param isLogin
	 * @param session
	 * @return
	 * @throws IOException
	 */
	private	boolean  checkToken(ServletRequest request, HttpServletResponse res, String appToken, boolean isLogin, Map<String, Object> session) throws IOException {
        Map<String,String> result = new HashMap<String,String>();

        result.put(ISystemConstant.AJAX_STATUS,ISystemConstant.AJAX_RESULT_SUCCESS);
	    //检查是否appTolen是否相同
		if(!isLogin) {
			result.put(ISystemConstant.AJAX_STATUS,ISystemConstant.AJAX_RESULT_FAIL);
	        result.put(ISystemConstant.AJAX_CODE,ISystemConstant.AJAX_CODE_NOLOGIN);
	        result.put(ISystemConstant.AJAX_MESSAGE,"尚未登录!");
			printResponse(res, result);
			return true;
		}
		if(StringHelper.isEmpty(appToken)){
			result.put(ISystemConstant.AJAX_STATUS,ISystemConstant.AJAX_RESULT_FAIL);
			result.put(ISystemConstant.AJAX_CODE,ISystemConstant.AJAX_CODE_NOTOKEN);
			result.put(ISystemConstant.AJAX_MESSAGE,"缺少appToken!");
			printResponse(res, result);
			return true;
		}
		if(!appToken.equals(session.get(ISystemConstant.CURRENT_APP_TOKEN))){
			result.put(ISystemConstant.AJAX_STATUS,ISystemConstant.AJAX_RESULT_FAIL);
			result.put(ISystemConstant.AJAX_CODE,ISystemConstant.AJAX_CODE_TOKEN_ERROR);
			result.put(ISystemConstant.AJAX_MESSAGE,"appToken错误!");
			printResponse(res, result);
            return true;
		}
		return false;
	}

	/**
	 * 打印应答结果
	 * @param res
	 * @param result
	 */
	private void printResponse(HttpServletResponse res, Map<String, String> result) throws IOException {
		res.getWriter().print(JSON.toJSONString(result));
	}

	/**
	 * 设置应答允许跨域
	 * @param request
	 * @param response
	 */
	private void setResponseAllOrigin(ServletRequest request,HttpServletResponse response) {
		HttpServletRequest httpRequest = (HttpServletRequest)request;
		response.setHeader("Access-Control-Allow-Origin", httpRequest.getHeader("Origin"));
		response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
		response.setHeader("Access-Control-Max-Age", "3600");
//		response.setHeader("Access-Control-Allow-Headers", "content-type"); //注意此处
		response.setHeader("Access-Control-Allow-Credentials", "true"); // 是否支持cookie跨域
		response.setHeader("Access-Control-Allow-Headers","content-type,app_token,id,sessionid");
		response.setHeader("Access-Control-Request-Headers", "Origin, X-Requested-With, content-Type, Accept, Authorization,app_token,sessionid");
//		response.addHeader("Access-Control-Request-Headers","app_token");


	}

	private void initConfig() {
		//查询数据库，获取过滤规则 
		Map<String, Object> searchVo = new HashMap<String,Object>();
		searchVo.put("CODE_TYPE_ID",ISystemConstant.PARAMETER_LOGIN_URL_ID);
		List<Map> maps = SecurityDBClientService.getInstance().search(DBSessionService.getSingleInstance().getSession(), "rm_code_data", searchVo);
		
		//循环加入needLoginUrls
		needLoginUrls = new ArrayList<String>();
		if(maps!=null) {
			for(Map m:maps) {
				needLoginUrls.add((String)m.get("DATA_VALUE"));
			}
		}
		logger.info("needLoginUrls size:"+needLoginUrls.size());
		contextPath = ContextUtils.getConfigValue("server.contextpath");
	}

	@Override
	public void destroy() {
		if(needLoginUrls!=null ) {
			needLoginUrls.clear();
		}
	}

}
